package com.example.statistics.ui.customer

import android.os.Bundle
import com.example.statistics.R
import com.example.statistics.bean.Customer
import com.example.statistics.common.BaseLoadingListActivity
import com.example.statistics.net.UrlConfig
import com.example.statistics.utils.Constants
import com.example.statistics.utils.CustomerUtils
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.activityForResult
import com.google.gson.Gson
import com.jhj.slimadapter.SlimAdapter
import com.jhj.slimadapter.holder.ViewInjector
import kotlinx.android.synthetic.main.layout_search_bar.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult

class CustomerListActivity : BaseLoadingListActivity<Customer>() {

    var str: String? = null

    override val title: String
        get() = "联系人"
    override val url: String
        get() = UrlConfig.CUSTOMER_LIST
    override val itemLayoutRes: Int
        get() = R.layout.list_item_common_display
    override val inputSearch: Boolean
        get() = true
    override val inputSearchFunc: (Customer, String) -> Boolean = { data, str ->
        data.name.orEmpty().contains(str) || data.phoneOne.orEmpty().contains(str)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        str = intent.getStringExtra(Constants.DATA)
        if (str != Constants.SELECTOR) //
            et_search_input.setText(str.orEmpty())
        topBarRightImage {
            activityForResult<CustomerDetailActivity>() {
                refresh()
            }
        }


        GlobalScope.launch {
            CustomerUtils.query(this@CustomerListActivity) {
                val b = Gson().toJson(it.map { com.example.statistics.ui.customer.Customer(it.ID,it.name,it.phoneOne)})
                val a = it
            }
        }
    }

    override fun itemViewConvert(adapter: SlimAdapter, injector: ViewInjector, bean: Customer, position: Int) {
        injector.text(R.id.tv_title, "${bean.city} ${bean.name}")
                .text(R.id.tv_subtitle, bean.product)
                .visible(R.id.iv_image)
                .clicked {
                    if (str.isNullOrBlank()) {
                        activityForResult<CustomerDetailActivity>(
                                Constants.DATA to bean
                        ) {
                            refresh()
                        }
                    } else {
                        activityFinish(Constants.DATA to bean)
                    }

                }
        //    .glideCircle(R.id.iv_avatar, bean.avatar)
    }


}

data class Customer(var id: Int, var name: String?, var phone: String?)